Ext.ns('AIR2.UI');
/***************
 * AIR2 RemoteText Component
 *
 * An Ext.form.TextField with automatic remote (ajax) validation
 *
 * @class AIR2.UI.RemoteText
 * @extends Ext.form.TextField
 * @xtype air2remotetext
 * @cfg {String} remoteUrl
 *   The remote validation url. In AIR2, this is usually something
 *   similar to: "AIR2.HOMEURL + '/foobar/name.json'", and is used to validate
 *   unique names.
 *
 */
AIR2.UI.RemoteText = function(cfg) {
    if (!cfg.remoteUrl) {
        Logger("ERROR: no remote URL Defined!!");
        return;
    }
    AIR2.UI.RemoteText.superclass.constructor.call(this, cfg);
}
Ext.extend(AIR2.UI.RemoteText, Ext.form.TextField, {
    remoteUrl: null,
    params: {},
    method: 'GET',
    timeout: 30 * 1000, /* ms */
    serverErrorText: 'ERROR: validation error',
    ajaxErrorText: 'ERROR: connection error',
    onRender: function(ct, position) {
        AIR2.UI.RemoteText.superclass.onRender.call(this, ct, position);
        this.remoteAction = ct.createChild({cls: 'air2-form-remote-wait'});
    },
    
    // TODO this copied verbatim from liveeditor.js
    // refactor into common ui/errormsg.js class
    showError: function(title, msg) {
        var el = this.el.insertSibling({
            tag: 'span',
            cls: 'air2-api-error-msg air2-corners',
            html: '<div class="title"><b>'+title+'</b></div>' +
                '<div class="msg"><p>'+msg+'</p></div>' +
                '<div class="btns"></div>'
        });
        var btn = new AIR2.UI.Button({
            air2type: 'DELETE',
            air2size: 'MEDIUM',
            text: 'Okay',
            renderTo: el.child('.btns', false),
            handler: function() {
                el.slideOut('t', {duration:.2, remove:true});
                btn.destroy();
            }
        });
        el.alignTo(this.el, 't-t');
        el.slideIn('t', {duration:.2});

    },
    doRemoteValidation: function(value) {
        // abort any previous requests
        if (this.ajaxId) {
            Ext.Ajax.abort(this.ajaxId);
            this.ajaxId = false;
        }

        // align the 'remote processing' element
        this.remoteAction.alignTo(this.el, 'tr-tl', [0,2]);
        this.remoteAction.show();

        // fire the remote request
        this.params.q = value;
        this.ajaxId = Ext.Ajax.request({
            method: this.method,
            url: this.remoteUrl,
            params: this.params,
            timeout: this.timeout,
            scope: this,
            callback: function(opts, success, resp) {
                this.ajaxId = false;
                this.remoteAction.hide();
                if (success) {
                    var data = Ext.util.JSON.decode(resp.responseText);
                    if (data.success) {
                        if (data.total == 0) {
                            this.remoteIsValid = true;
                            this.remoteMsg = '';
                        }
                        else {
                            this.remoteIsValid = false;
                            this.remoteMsg = 'Name already in use';
                        }
                    }
                    else {
                        this.remoteIsValid = false;
                        this.remoteMsg = this.serverErrorText;
                    }
                }
                else {
                    this.remoteIsValid = false;
                    this.remoteMsg = this.ajaxErrorText;
                }
                this.preventMark = false; // now allow marking
                this.validate(); // refire the validation
            }
        });
    },
    validator: function(value) {
        if (this.originalValue === null && value.length > 0)
            this.originalValue = value;

        if (value == this.originalValue) return true;

        // fire remote validation if value has changed
        if (value != this.lastValue) {
            this.preventMark = true; //don't mark until callback
            this.lastValue = value;
            this.remoteIsValid = false;
            this.doRemoteValidation(value);
        }

        return (this.remoteIsValid) ? true : this.remoteMsg;
    },
    reset: function() {
        this.originalValue = null; // allow changing originalValue on reset
        AIR2.UI.RemoteText.superclass.reset.call(this);
    }
});
Ext.reg('air2remotetext', AIR2.UI.RemoteText);
